package com.hc.file.service;

import com.hc.common.core.exception.file.InvalidExtensionException;
import com.hc.common.core.utils.file.MimeTypeUtils;
import com.hc.common.security.service.TokenService;
import com.hc.file.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 本地文件存储
 * 
 * @author ruoyi
 */
@Primary
@Service
public class LocalSysFileServiceImpl implements ISysFileService
{

    @Autowired
    private TokenService tokenService;
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;


    /**
     * 网关访问地图地址D
     */
    @Value("${file.mapDomain}")
    public String mapDomain;
    
    /**
     * 上传文件存储在本地的根路径D
     */
    @Value("${file.path}")
    private String localFilePath;

    /**
     * 本地文件上传接口
     * 
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    public String uploadFile(MultipartFile file) throws Exception
    {
        String name = FileUploadUtils.upload(localFilePath, file);
        String url = domain + localFilePrefix + name;
        return url;
    }

    @Override
    public String uploadMap(MultipartFile file) throws IOException, InvalidExtensionException {
        String tenantNameSpace = "/"+tokenService.getLoginUser().getDataSourceName();
        String baseDir = localFilePath + "/" + tenantNameSpace;
        String name = FileUploadUtils.uploadMap(baseDir, file, MimeTypeUtils.MAP_EXTENSION);
        String url = mapDomain + localFilePrefix + tenantNameSpace + name;
        return url;
    }


}
